<template>
  <div class="app-container">
    <wms-form v-model:query-params="queryParams" :form-list="formList" @query="getList" @export="handleExport">
      <el-col :span="1.5">
        <el-button type="danger" plain :disabled="multiple" @click="disables('frozen')">一键冻结
        </el-button>
        <el-button type="success" plain :disabled="multiple" @click="disables('unfrozen')">一键解冻
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" :disabled="multiple" @click="directOutTask">原材直发出库</el-button>
      </el-col>
    </wms-form>
    <wms-table :loading="loading" :data-list="stockList" :column="column" :pageInfo="queryParams" @get-list="getList"
      @selection-change="handleSelectionChange" />
  </div>
</template>

<script setup name="Stock">
import { listStock, disablesStock, directOut } from "@/api/wms/stock";
import WmsForm from '@/components/WmsForm/index.vue'
import WmsTable from '@/components/WmsTable/index.vue'
import { data, column, formList } from './index.js'
import { ref, reactive, getCurrentInstance, onMounted } from "vue";

const { proxy } = getCurrentInstance();
const queryParams = reactive(data.queryParams);
const stockList = ref([]);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const selectedStocks = ref([]);

/** 查询库存查询列表 */
function getList() {
  loading.value = true;
  listStock(proxy.addDateRange(queryParams, queryParams.dateRange)).then(response => {
    stockList.value = response.rows;
    queryParams.total = response.total;
    loading.value = false;
  });
}


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.dateRange = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.stockId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  selectedStocks.value = selection;
}

// 暴露选中的库存项
defineExpose({
  getSelectedStocks: () => selectedStocks.value
})

/** 导出按钮操作 */
function handleExport() {
  proxy.download('${moduleName}/${businessName}/export', {
    ...queryParams
  }, `${businessName}_#[[${new Date().getTime()}.xlsx`)
}
/** 一键冻结解冻按钮操作 */
async function disables(type) {
  // 修正状态值逻辑：冻结->1，解冻->0
  const isFreeze = type === 'frozen'; // 判断是否是冻结操作
  const status = type === 'frozen' ? '1' : '0';
  const actionName = type === 'frozen' ? '冻结' : '解冻';

  try {
    let lockReason = ''; // 存储冻结原因

    // 冻结操作需要输入原因
    if (isFreeze) {
      // 弹出带有输入框的确认对话框
      const result = await ElMessageBox.prompt(
        '请输入冻结原因：',
        `确定要冻结选中的【 ${ids.value.length} 】条库存吗？`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          inputType: 'textarea',
          inputPlaceholder: '请详细说明冻结原因',
          inputValidator: (value) => {
            // 验证输入不能为空
            if (!value || value.trim() === '') {
              return '冻结原因不能为空';
            }
            return true;
          }
        }
      );

      // 获取输入的冻结原因
      lockReason = result.value;
    } else {
      // 解冻操作使用普通确认框
      await ElMessageBox.confirm(
        `确定要解冻选中的 ${ids.value.length} 条库存吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
    }

    // 调用API方法
    const response = await disablesStock({
      ids: ids.value,
      status: status, // 传递正确的状态参数
      lockReason: lockReason
    });
    console.log("完整响应:", response);
    getList(); // 使用已有的刷新方法
  } catch (error) {
    console.log('操作已取消', error);
  }
}

async function directOutTask() {

  try {
    await ElMessageBox.confirm(
      `确定要生成选中的 ${ids.value.length} 条库存的出库任务吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 调用原材直发出库任务的API
    const response = await directOut({
      ids: ids.value
    });
    // if (response.code === 200) {
    //   ElMessage.success('原材直发出库任务创建成功');
    //   getList(); // 刷新盘点任务列表
    // } else {
    //   ElMessage.error(response.msg || '创建失败');
    // }
    ElMessage.success('出库任务创建成功');
    getList(); // 刷新盘点任务列表
  } catch (error) {
    console.error('创建出库任务失败:', error);
    // ElMessage.error(error);
  }
}
getList();
</script>
